const pool = require('../models/db');

const categoryController = {
    // 获取所有分类
    getAllCategories: async (req, res) => {
        try {
            const [categories] = await pool.query(`
                SELECT c.*, 
                       COUNT(a.id) as article_count
                FROM categories c
                LEFT JOIN articles a ON c.id = a.category_id
                GROUP BY c.id
                ORDER BY c.name
            `);
            res.json(categories);
        } catch (error) {
            res.status(500).json({ error: error.message });
        }
    },

    // 获取单个分类
    getCategoryById: async (req, res) => {
        try {
            const [categories] = await pool.query(
                'SELECT * FROM categories WHERE id = ?',
                [req.params.id]
            );

            if (categories.length === 0) {
                return res.status(404).json({ message: '分类不存在' });
            }

            res.json(categories[0]);
        } catch (error) {
            res.status(500).json({ error: error.message });
        }
    },

    // 获取分类下的所有文章
    getCategoryArticles: async (req, res) => {
        try {
            const [articles] = await pool.query(`
                SELECT a.*, 
                       u.username as author_name,
                       GROUP_CONCAT(t.name) as tags
                FROM articles a
                LEFT JOIN users u ON a.author_id = u.id
                LEFT JOIN article_tags at ON a.id = at.article_id
                LEFT JOIN tags t ON at.tag_id = t.id
                WHERE a.category_id = ? AND a.status = 'published'
                GROUP BY a.id
                ORDER BY a.created_at DESC
            `, [req.params.id]);

            articles.forEach(article => {
                article.tags = article.tags ? article.tags.split(',') : [];
            });

            res.json(articles);
        } catch (error) {
            res.status(500).json({ error: error.message });
        }
    },

    // 创建分类
    createCategory: async (req, res) => {
        try {
            const { name, icon, description } = req.body;
            const [result] = await pool.query(
                'INSERT INTO categories (name, icon, description) VALUES (?, ?, ?)',
                [name, icon, description]
            );

            res.status(201).json({
                message: '分类创建成功',
                categoryId: result.insertId
            });
        } catch (error) {
            if (error.code === 'ER_DUP_ENTRY') {
                return res.status(400).json({ message: '分类名称已存在' });
            }
            res.status(500).json({ error: error.message });
        }
    },

    // 更新分类
    updateCategory: async (req, res) => {
        try {
            const { name, icon, description } = req.body;
            const [result] = await pool.query(
                'UPDATE categories SET name = ?, icon = ?, description = ? WHERE id = ?',
                [name, icon, description, req.params.id]
            );

            if (result.affectedRows === 0) {
                return res.status(404).json({ message: '分类不存在' });
            }

            res.json({ message: '分类更新成功' });
        } catch (error) {
            if (error.code === 'ER_DUP_ENTRY') {
                return res.status(400).json({ message: '分类名称已存在' });
            }
            res.status(500).json({ error: error.message });
        }
    },

    // 删除分类
    deleteCategory: async (req, res) => {
        try {
            const [result] = await pool.query(
                'DELETE FROM categories WHERE id = ?',
                [req.params.id]
            );

            if (result.affectedRows === 0) {
                return res.status(404).json({ message: '分类不存在' });
            }

            res.json({ message: '分类删除成功' });
        } catch (error) {
            if (error.code === 'ER_ROW_IS_REFERENCED') {
                return res.status(400).json({ 
                    message: '该分类下还有文章，无法删除' 
                });
            }
            res.status(500).json({ error: error.message });
        }
    }
};

module.exports = categoryController;